package com.clkj.mobileinspector.ui.fragment;

import android.graphics.Color;
import android.text.TextUtils;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.Spinner;

import com.bigkoo.pickerview.builder.TimePickerBuilder;
import com.bigkoo.pickerview.listener.OnTimeSelectListener;
import com.bigkoo.pickerview.view.TimePickerView;
import com.clkj.mobileinspector.R;
import com.clkj.mobileinspector.model.Constant;
import com.clkj.mobileinspector.model.ObserverOnNext;
import com.clkj.mobileinspector.model.OkHttpUtils;
import com.clkj.mobileinspector.model.bean.PolicedeptBean;
import com.clkj.mobileinspector.model.bean.ProblemtypeBean;
import com.clkj.mobileinspector.model.bean.QueryBean;
import com.clkj.mobileinspector.model.bean.QuerySuccessBean;
import com.clkj.mobileinspector.model.bean.ResourceApi;
import com.clkj.mobileinspector.ui.activity.MainActivity;
import com.clkj.mobileinspector.ui.activity.StatisticsActivity;
import com.clkj.mobileinspector.utils.JsonUtils;
import com.clkj.mobileinspector.utils.LogUtils;
import com.clkj.mobileinspector.utils.ResourceApiUtils;
import com.github.mikephil.charting.charts.BarChart;
import com.github.mikephil.charting.components.XAxis;
import com.github.mikephil.charting.components.YAxis;
import com.github.mikephil.charting.data.BarData;
import com.github.mikephil.charting.data.BarDataSet;
import com.github.mikephil.charting.data.BarEntry;
import com.github.mikephil.charting.formatter.ValueFormatter;
import com.github.mikephil.charting.interfaces.datasets.IBarDataSet;
import com.google.gson.reflect.TypeToken;
import com.lws.basic.base.BaseFragment;
import com.lws.basic.utils.common.GsonUtils;
import com.lws.basic.utils.common.MyLogger;
import com.lws.basic.utils.common.MyToast;
import com.lws.basic.utils.common.TimeUtils;

import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.Unbinder;

import static com.clkj.mobileinspector.utils.JsonUtils.queryGetFiled;

/**
 * @author 松
 * 2020/10/7 10:49
 * 类型对比
 */
public class TypeContrastFragment extends BaseFragment {
    @BindView(R.id.et_start)
    EditText mEtStart;
    @BindView(R.id.et_end)
    EditText mEtEnd;
    @BindView(R.id.sp_type)
    Spinner mSpType;
    @BindView(R.id.rb_1)
    RadioButton mRb1;
    @BindView(R.id.rb_2)
    RadioButton mRb2;
    @BindView(R.id.rg_type)
    RadioGroup mRgType;
    @BindView(R.id.carChart)
    BarChart mCarChart;
    Unbinder mUnbinder;
    private String mTypeId;   //类型id
    private String mTypeName; // 类型名称


    @Override
    public int setLayoutId() {
        return R.layout.fragment_type_contrast;
    }

    @Override
    protected void initView(View rootView) {
        super.initView(rootView);
        mUnbinder = ButterKnife.bind(this, rootView);
    }

    @Override
    protected void initData() {
        super.initData();
        initSpinner(((StatisticsActivity) getActivity()).getSpList());
        getData(search());


    }

    /**
     * 获取数据
     */
    private void getData(List<QueryBean.ParameterBean.ConditionBean.KeyValueListBean> keyValueListBeanList) {
        ResourceApi typeChart = ResourceApiUtils.getResourceApi(MainActivity.resourceApiList, Constant.typeChart);


        showLoading();
        List<QueryBean.ParameterBean.OrderByBean> orderByList = new ArrayList<>();
//        QueryBean.ParameterBean.OrderByBean order1 = new QueryBean.ParameterBean.OrderByBean();
//        order1.setSort("passdate");
//        order1.setSort("desc");
//        orderByList.add(order1);

        QueryBean.ParameterBean.PageBean page = new QueryBean.ParameterBean.PageBean();
        page.setPageNo(1);
        page.setPageSize(1000);

        String json = JsonUtils.query(keyValueListBeanList, "deptname,inspectiontotal"
                , typeChart.getResourceId(), orderByList, page, typeChart.getResourceRegionalismCode());
        LogUtils.logUpload("类型对比", "1", typeChart.getResourceId(), typeChart.getResourceAddress(), json, "", "成功", "", "");

        OkHttpUtils.post(typeChart.getResourceAddress(), json, QuerySuccessBean.class).subscribe(new ObserverOnNext<QuerySuccessBean>() {
            @Override
            public void onNext(QuerySuccessBean querySuccessBean) {
                dismissLoading();

                if (querySuccessBean.getCode().equals("200")) {

//                    querySuccessBean.getData().getDataList().add(querySuccessBean.getData().getDataList().get(0));
//                    querySuccessBean.getData().getDataList().add(querySuccessBean.getData().getDataList().get(0));
//                    querySuccessBean.getData().getDataList().add(querySuccessBean.getData().getDataList().get(0));
//                    querySuccessBean.getData().getDataList().add(querySuccessBean.getData().getDataList().get(0));
//                    querySuccessBean.getData().getDataList().add(querySuccessBean.getData().getDataList().get(0));

                    initBarChart(mTypeName, querySuccessBean.getData().getDataList());
                } else {
                    MyToast.show(querySuccessBean.getMessage());
                }
            }
        });
    }


    /**
     * 搜索条件
     */
    private List<QueryBean.ParameterBean.ConditionBean.KeyValueListBean> search() {
        String start = mEtStart.getText().toString();//
        String end = mEtEnd.getText().toString();//
        if (!TextUtils.isEmpty(end)) {
            end += " 23:59:59";
        }
        List<QueryBean.ParameterBean.ConditionBean.KeyValueListBean> list = new ArrayList<>();
        if (!mTypeId.equals("0")) {
            QueryBean.ParameterBean.ConditionBean.KeyValueListBean bean1 = new QueryBean.ParameterBean.ConditionBean.KeyValueListBean();
            bean1.setKey("inspecttype");
            bean1.setRelationOperator("=");
            bean1.setValue(mTypeId);
            list.add(bean1);
        }
        QueryBean.ParameterBean.ConditionBean.KeyValueListBean bean2 = new QueryBean.ParameterBean.ConditionBean.KeyValueListBean();
        bean2.setKey("depttype");
        bean2.setRelationOperator("=");
        if (mRb1.isChecked()) {

            bean2.setValue("1");

        } else {
            bean2.setValue("2");
        }
        list.add(bean2);
        QueryBean.ParameterBean.ConditionBean.KeyValueListBean bean3 = new QueryBean.ParameterBean.ConditionBean.KeyValueListBean();
        bean3.setKey("starttime");
        bean3.setRelationOperator(">=");
        bean3.setValue(start);
        list.add(bean3);
        QueryBean.ParameterBean.ConditionBean.KeyValueListBean bean4 = new QueryBean.ParameterBean.ConditionBean.KeyValueListBean();
        bean4.setKey("endtime");
        bean4.setRelationOperator("<=");
        bean4.setValue(end);
        list.add(bean4);
        return list;
    }


    /**
     * 初始化下拉列表
     */
    private void initSpinner(List<QuerySuccessBean.DataBean.DataListBean.FieldValuesBean> list) {
        try {

            //类型下拉列表
            String problemtype = JsonUtils.queryGetFiled(list, "problemtype");
            Type type = new TypeToken<List<ProblemtypeBean>>() {
            }.getType();
            List<ProblemtypeBean> problemtypeBeanList = GsonUtils.getInstance().fromJson(problemtype, type);
            List<String> typeList = new ArrayList<>();
            typeList.add("全部");
            for (ProblemtypeBean bean : problemtypeBeanList) {
                typeList.add(bean.getName());
            }
            mTypeName = "全部";
            //默认类型id
            mTypeId = "0";
            //类型
            ArrayAdapter adapterType = new ArrayAdapter<String>(getActivity(), android.R.layout.simple_spinner_dropdown_item, typeList);
            mSpType.setAdapter(adapterType);
            mSpType.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
                @Override
                public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                    MyLogger.i(position + "");
                    if (position == 0) {
                        mTypeId = "0";
                    } else {
                        mTypeId = problemtypeBeanList.get(position - 1).getId() + "";
                        mTypeName = problemtypeBeanList.get(position - 1).getName();
                    }
                }

                @Override
                public void onNothingSelected(AdapterView<?> parent) {

                }
            });


        } catch (Exception e) {
            MyToast.show(e.getMessage());
            MyLogger.i("统计分析下拉列表" + e.getMessage());
        }


    }


    /**
     * 柱状图
     */
    private void initBarChart(String label, List<QuerySuccessBean.DataBean.DataListBean> list) {
        mCarChart.getDescription().setEnabled(false); // 不显示描述
        mCarChart.setExtraOffsets(00, 20, 20, 20); // 设置饼图的偏移量，类似于内边距 ，设置视图窗口大小
        mCarChart.setScaleEnabled(true);//是否可以缩放


//        //设置图表编译，避免x轴标签显示不全
        //      mCarChart.setExtraBottomOffset(10);
//        //禁用图例
//        mCarChart.getLegend().setEnabled(false);
//        //禁用描述

        // 设置坐标轴
        setData(label, list);  // 设置数据
    }

    /**
     * 因为此处的 barData.setBarWidth(0.3f);，也就是说柱子的宽度是0.3f
     * 所以第二个柱子的值要比第一个柱子的值多0.3f，这样才会并列显示两根柱子
     */
    private void setData(String label, List<QuerySuccessBean.DataBean.DataListBean> list) {
        try {


            //setAxis();
            List<IBarDataSet> sets = new ArrayList<>();
            //添加数据
            List<BarEntry> barEntries1 = new ArrayList<>();
            String labelName[] = new String[list.size()];
            MyLogger.i(list.size() + "数组大小");
            int nmuber = 0;
            for (int i = 0; i < list.size(); i++) {

//                if (TextUtils.isEmpty(queryGetFiled(list.get(i).getFieldValues(), "inspectiontotal"))) {
//                    barEntries1.add(new BarEntry(i, 0));
//
//                } else {
                try {
                    labelName[i] = queryGetFiled(list.get(i).getFieldValues(), "deptname");
                    barEntries1.add(new BarEntry(i, Integer.valueOf(queryGetFiled(list.get(i).getFieldValues(), "inspectiontotal"))));
                    if (nmuber < Integer.valueOf(queryGetFiled(list.get(i).getFieldValues(), "inspectiontotal"))) {
                        nmuber = Integer.valueOf(queryGetFiled(list.get(i).getFieldValues(), "inspectiontotal"));
                    }
                } catch (Exception e) {
                    MyLogger.i("类型对比：报错" + e.getMessage());
                }
                //}

            }

            if (nmuber <= 10) {
                nmuber = 10;
            } else if (nmuber > 10 && nmuber <= 100) {
                if (nmuber!=100){
                       String decade = (nmuber+"").substring(0,1);
                       nmuber = Integer.valueOf( ((Integer.valueOf(decade)+1)+"0"));
                }
            } else if (nmuber > 100 && nmuber <= 1000) {
                if (nmuber!=1000){
                    String decade = (nmuber+"").substring(0,1);
                    nmuber = Integer.valueOf( ((Integer.valueOf(decade)+1)+"00"));
                }
            } else {

            }

            setAxis(labelName, nmuber);


            BarDataSet barDataSet1 = new BarDataSet(barEntries1, "");

            barDataSet1.setValueTextColor(Color.BLACK); // 柱状图上值的颜色
            barDataSet1.setValueTextSize(12f); // 柱状图上值的大小

            barDataSet1.setLabel(label);
            barDataSet1.setColor(getResources().getColor(R.color.color_main));

            sets.add(barDataSet1);


            BarData barData = new BarData(sets);
            barData.setBarWidth(0.5f); // 设置柱子的宽度

            barDataSet1.setValueFormatter(new ValueFormatter() {
                @Override
                public String getFormattedValue(float value) {
                    return ((int) value) + "";
                }
            });
            mCarChart.setData(barData);
            mCarChart.invalidate();
        } catch (Exception e) {
            MyToast.show(e.getMessage());
        }


    }

    /**
     * 因为此处的 barData.setBarWidth(0.3f);，也就是说柱子的宽度是0.3f
     * 所以第二个柱子的值要比第一个柱子的值多0.3f，这样才会并列显示两根柱子
     */
    private void setData1(String label, List<QuerySuccessBean.DataBean.DataListBean> list) {
        try {


            List<IBarDataSet> sets = new ArrayList<>();
            //添加数据

            String labelName[] = new String[list.size()];

            for (int i = 0; i < list.size(); i++) {

                try {
                    List<BarEntry> barEntries1 = new ArrayList<>();
                    labelName[i] = queryGetFiled(list.get(i).getFieldValues(), "deptname");
                    barEntries1.add(new BarEntry(i, Integer.valueOf(queryGetFiled(list.get(i).getFieldValues(), "inspectiontotal"))));


                    BarDataSet barDataSet1 = new BarDataSet(barEntries1, "");

                    barDataSet1.setValueTextColor(Color.BLACK); // 柱状图上值的颜色
                    barDataSet1.setValueTextSize(12f); // 柱状图上值的大小

                    barDataSet1.setLabel(label);
                    barDataSet1.setColor(getResources().getColor(R.color.color_main));

                    sets.add(barDataSet1);


                } catch (Exception e) {
                    MyLogger.i("类型对比：报错" + e.getMessage());
                }


            }


            setAxis(labelName, 0);


            BarData barData = new BarData(sets);
            barData.setBarWidth(0.5f); // 设置柱子的宽度
            barData.setValueFormatter(new ValueFormatter() {
                @Override
                public String getFormattedValue(float value) {
                    return ((int) value) + "111111";
                }
            });

            mCarChart.setData(barData);
            barData.setValueFormatter(new ValueFormatter() {
                @Override
                public String getFormattedValue(float value) {
                    return ((int) value) + "111111";
                }
            });
            mCarChart.invalidate();
        } catch (Exception e) {
            MyToast.show(e.getMessage());
        }


    }

    /**
     * 柱形
     */
    private void setAxis(String labelName[], int number) {
        // 设置x轴
        XAxis xAxis = mCarChart.getXAxis();
        xAxis.setPosition(XAxis.XAxisPosition.BOTTOM);  // 设置x轴显示在下方，默认在上方
        xAxis.setDrawGridLines(false); // 将此设置为true，绘制该轴的网格线。
        //  xAxis.setLabelCount(4);  // 设置x轴上的标签个数
        xAxis.setTextSize(10); // x轴上标签的大小
        xAxis.setLabelCount(labelName.length, false);

        //设置x轴下方名称
        MyLogger.i(labelName.length + " 类型对比下标  ");
        xAxis.setValueFormatter(new ValueFormatter() {
            @Override
            public String getFormattedValue(float value) {
                return labelName[(int) value];
            }

        });

        //  xAxis.setLabelCount(labelName.length);
        // 设置y轴，y轴有两条，分别为左和右
        YAxis yAxis_right = mCarChart.getAxisRight();
        yAxis_right.setEnabled(false);  // 不显示右边的y轴

        YAxis yAxis_left = mCarChart.getAxisLeft();
        yAxis_left.setAxisMaximum(number);
        yAxis_left.setAxisMinimum(0); //
        yAxis_left.setTextSize(12); // 设置y轴的标签大小
        // yAxis_left.setDrawGridLines(false); //设置y内横线显示


    }


    @Override
    public void onDestroy() {
        super.onDestroy();
        mUnbinder.unbind();
    }


    @OnClick({R.id.et_start, R.id.et_end, R.id.btn_search})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.et_start:
                showTime(1);
                break;
            case R.id.et_end:
                showTime(2);
                break;
            case R.id.btn_search:
                getData(search());
                break;
        }
    }

    /**
     * 显示时间
     */
    private void showTime(int flag) {
        TimePickerView pvTime = new TimePickerBuilder(getContext(), new OnTimeSelectListener() {
            @Override
            public void onTimeSelect(Date date, View v) {
                String time = TimeUtils.date2date(date);
                //1开始时间
                if (flag == 1) {
                    mEtStart.setText(time);
                }
                //结束时间
                if (flag == 2) {
                    mEtEnd.setText(time);
                }

                MyLogger.i(TimeUtils.date2date(date));

            }
        }).setType(new boolean[]{true, true, true, false, false, false})// 默认全部显示
                .setCancelText("取消")//取消按钮文字
                .setSubmitText("确定")//确认按钮文字
                .setOutSideCancelable(false)//点击屏幕，点在控件外部范围时，是否取消显示
                .isCyclic(true)//是否循环滚动
                .setBgColor(0xffd6ecf0)
                .setTitleBgColor(0xffd6ecf0)
                .setLabel("年", "月", "日", "", "", "")//默认设置为年月日时分秒
                .isCenterLabel(true) //是否只显示中间选中项的label文字，false则每项item全部都带有label。
                .isDialog(true)//是否显示为对话框样式
                .build();

        pvTime.show();
    }

}
